package com.neuedu.myshuffle;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

/**
 * 词频统计：shuffle
 *
 * @author
 * @create
 */

public class WordCount1 {
    public static void main(String[] args) {
        try {
            Configuration conf = new Configuration();
            FileSystem hdfs = FileSystem.get(conf);
            String input = "/books";
            String output = "/wordcount";
            Path outputPath = new Path(output);
            // 判断输出目录是否存在，存在则删除之
            if (hdfs.exists(outputPath)) {
                hdfs.delete(outputPath, true);
            }
            // 创建Job任务
            Job job = Job.getInstance(conf, "word count");
            //设置输入
            job.setInputFormatClass(TextInputFormat.class);
            FileInputFormat.setInputPaths(job, input);
            // 设置mapper
            job.setMapperClass(WordCountMapper.class);
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(IntWritable.class);
            //设置分区
            job.setNumReduceTasks(3);
            job.setPartitionerClass(WordCountPartitioner.class);
            // 设置combiner
            job.setCombinerClass(WordCountCombiner.class);
            //自定义排序
            job.setSortComparatorClass(TextByDescComparator.class);
            // 设置分组
            job.setGroupingComparatorClass(TextByGrouping.class);
            //设置reducer
            job.setReducerClass(WordCountReducer.class);
            // 设置输出:下面2行容易写错
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);
            job.setOutputFormatClass(TextOutputFormat.class);
            FileOutputFormat.setOutputPath(job, outputPath);
            // 运行
            Boolean flag = job.waitForCompletion(true);
            if (flag) {
                System.out.println("词频统计结束~~~");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            String line = value.toString();
            if (StringUtils.isBlank(line)) {
                return;
            }
            String[] items = line.split(" ");
            for (String word : items) {
                System.out.println("map:" + word);
                context.write(new Text(word), new IntWritable(1));
            }
        }
    }

    public static class WordCountPartitioner extends Partitioner<Text, IntWritable> {
        @Override
        public int getPartition(Text key, IntWritable value, int numPartitions) {
            int hash = Math.abs(key.hashCode());
            System.out.println("partition:" + key + ", " + hash % numPartitions);
            return hash % numPartitions;
        }
    }

    public static class WordCountCombiner extends Reducer<Text, IntWritable, Text, IntWritable> {
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            System.out.println("combiner:" + key + ":" + sum);
            context.write(key, new IntWritable(sum));
        }
    }

    public static class TextByDescComparator extends Text.Comparator {
        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
            System.out.println("compare:" + new String(b1, s1, l1) + "," + new String(b2, s2, l2));
            return -super.compare(b1, s1, l1, b2, s2, l2);
        }
    }

    public static class TextByGrouping extends WritableComparator {
        public TextByGrouping() {
            super(Text.class, true);
        }

        @Override
        public int compare(WritableComparable a, WritableComparable b) {
            Text t1 = (Text) a;
            Text t2 = (Text) b;
            System.out.println("group:" + t1 + "," + t2);
            return t1.compareTo(t2);
        }
    }

    public static class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            System.out.println("reducer:" + key + ":" + sum);
            context.write(key, new IntWritable(sum));
        }
    }
}
